<template>
  <div class="h-[calc(100%-60px)]">
    <div class="flex h-[100%] pt-[8px]">
      <div class="overflow-auto w-[100%]">
        <div class="px-[8px] h-[100%]">
          <!-- <el-affix ref="affixRef" :offset="92"> -->
          <div
            v-if="channelTime.length"
            ref="container"
            class="bg-[var(--base-color)] text-[14px] py-[8px] px-[8px] border-b border-solid border-gray-300 whitespace-nowrap relative"
          >
            <span
              v-for="(item, index) in showChannelTime"
              :key="index"
              class="px-[15px] py-[6px] cursor-pointer mr-[8px] relative rounded-[4px]"
              :class="{
                'bg-[#eaf3ff] text-[#3487ff]':
                  item.channel_id === detailData.channel.id,
                'bg-[var(--base-small-bg-color)]': item.channel_id != detailData.channel.id,
              }"
              @click="handleTag(item.channel_id)"
            >
              <span>
                <svg-icon
                  v-if="item.channel_id === detailData.channel.id"
                  icon-class="state_wait_line1"
                  class="mr-[2px] inline-block"
                />
                <svg-icon v-else icon-class="state_wait_line" class="mr-[2px] inline-block"/>
              </span>
              <span>
                {{ formatTime(item.start_time) }} -
                {{ formatTime(item.end_time) }}
              </span>
              <svg-icon
                icon-class="new"
                class-name="icon"
                class="absolute text-[#fff] top-0 right-0"
                v-if="index == 0"
              />
            </span>
            <!-- </span> -->
            <el-dropdown
              class="absolute right-[16px]"
              v-if="hideChannelTime?.length"
            >
              <span
                class="border border-solid border-[#e6e7e9] border-1 py-[6px] px-[30px] text-[14px] text-middle cursor-pointer hover:bg-[#fafafa] rounded-[4px]"
                >更多 >></span
              >
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item
                    v-for="it in hideChannelTime"
                    :key="it"
                    @click="handleTag(it.channel_id)"
                  >
                    <span>
                      {{ formatTime(it.start_time) }} -
                      {{ formatTime(it.end_time) }}
                    </span>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
          <!-- </el-affix> -->
          <div
            class="flex rounded-bl-[8px] rounded-br-[8px] overflow-auto"
            :class="{ 'h-[calc(100%-45px)]': isEdit, 'h-[100%]': !isEdit }"
          >
            <div class="flex-1 bg-[var(--base-color)] px-[16px] h-[100%] rounded-[8px]">
              <el-tabs v-model="tabActive" @tab-change="handleChange">
                <el-tab-pane label="基本资料" name="1">
                  <BaseInfo
                    ref="baseRef"
                    v-show="+tabActive === 1"
                    v-bind="commonProps"
                    :data="channel_surcharge"
                  />
                </el-tab-pane>
                <el-tab-pane label="面单报关设置" name="2">
                  <DeclareBill
                    ref="declareBillRef"
                    v-show="+tabActive === 2"
                    v-bind="commonProps"
                    :data="detailData.channel_declare_bill"
                  />
                </el-tab-pane>
                <el-tab-pane label="附加属性" name="3">
                  <Additional
                    ref="additionalRef"
                    v-show="+tabActive === 3"
                    v-bind="commonProps"
                    :data="detailData.channel_attributes"
                    id="附加属性"
                  />
                </el-tab-pane>
                <el-tab-pane label="设置回邮地址" name="4">
                  <Address
                    ref="addressRef"
                    v-show="+tabActive === 4"
                    v-bind="commonProps"
                    :data="detailData.channel_address"
                  />
                </el-tab-pane>
                <el-tab-pane label="平台运输方式" name="5">
                  <TransportType
                    ref="transportTypeRef"
                    v-show="+tabActive === 5"
                    v-bind="commonProps"
                    :data="detailData.channel_transport_type"
                    id="平台运输方式"
                  />
                </el-tab-pane>
                <el-tab-pane label="日志" name="6" v-if="isEdit">
                  <Log
                    v-if="+tabActive === 6"
                    tag="channel.channel"
                    :business_id="id"
                    id="日志"
                  />
                </el-tab-pane>
              </el-tabs>
            </div>
            <div>
              <!-- <tabSteps :list="tabOptions" @activeIndex="handleActiveIndex"/> -->
              <steps :list="tabOptions" class="steps"></steps>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div
      class="flex items-center justify-center bg-[var(--base-color)] py-[10px] shadow-[0_-3px_6px_0_rgba(51,102,241,0.1)] relative z-10 ml-[8px]"
    >
      <el-button size="large" @click="handleCancel" :disabled="loading">
        取消
      </el-button>
      <el-button
        size="large"
        type="primary"
        @click="handleSave"
        :loading="loading"
      >
        保存
      </el-button>
    </div>
  </div>
</template>

<script setup lang="jsx">
import { ElMessage, dayjs } from "element-plus";
import Tab from "@/components/Tab/index.vue";
import Log from "@/components/Log/index.vue";
import BaseInfo from "./BaseInfo/index.vue";
import Additional from "./Additional/index.vue";
import DeclareBill from "./DeclareBill/index.vue";
import Address from "./Address/index.vue";
import TransportType from "./TransportType/index.vue";
import steps from "@/components/steps/index.vue";
import { strHump } from "@/utils/index";
import action from "@/utils/action.js";

import { overallOptions, getLogisticsAttr } from "@/api/public.js";
import { channelCreate, channelDetail, updateChannel } from "../api/index";

const router = useRouter();
const tabActive = ref("1");

const id = ref();
const detailData = ref({ channel: { id: "" } });
const loading = ref(false);
const baseRef = ref();
const declareBillRef = ref();
const additionalRef = ref();
const addressRef = ref();
const transportTypeRef = ref();
const channelTime = ref([]);

const optionsData = ref([]);

const isEdit = computed(() => !!detailData.value?.channel?.id);

const tabOptions = ref([
  { label: "基本信息" },
  // { label: "运价信息" },
  // { label: "附加费用信息" },
]);

const commonProps = computed(() => ({
  id: id.value,
  options: optionsData.value,
}));

// watch(
//   () => isEdit.value,
//   (val) => {
//     if (!val) return;
//     tabOptions.push({
//       label: "日志",
//       value: "6",
//     });
//   },
//   { immediate: true }
// );
const container = ref();
const hasOverflow = ref(false);
const showChannelTime = ref([]);
const hideChannelTime = ref([]);
watch(
  () => channelTime.value,
  (val) => {
    if (val) {
      nextTick(() => {
        handleResize();
      });
    }
  }
);
onMounted(() => {
  getOptions();
  const { id: idQuery } = router.currentRoute.value.query || {};
  if (idQuery) {
    id.value = idQuery;
    nextTick(() => getDetail());
  }
  window.addEventListener("resize", handleResize);
});
const handleResize = () => {
  let ind = Math.floor((container.value?.clientWidth - 120) / 298);
  hasOverflow.value = ind < channelTime.value?.length;
  showChannelTime.value = channelTime.value?.slice(0, ind);
  hideChannelTime.value = channelTime.value?.slice(ind);
};
const formatTime = (time) => {
  return dayjs(time).isValid() ? dayjs(time).format("YY-MM-DD HH:mm:ss") : "";
};
const channel_surcharge = reactive({
  channel: {},
  surcharge: [],
});
const onlyData = ref([]);
const getDetail = async (_id) => {
  try {
    loading.value = true;
    const { data } = await channelDetail({ id: _id || id.value });
    detailData.value = data;
    onlyData.value = JSON.parse(JSON.stringify(data?.channel_surcharge || []));
    channel_surcharge.channel = data?.channel || {};
    channel_surcharge.surcharge = data?.channel_surcharge || [];
    if (!_id) {
      channelTime.value = data?.channel_time || [];
    }
  } catch (e) {
    console.warn(e);
  } finally {
    loading.value = false;
  }
};

const handleTag = (id) => {
  getDetail(id);
};

const getOptions = async () => {
  try {
    const params = "channel.channel";
    const bill = "base.bill";
    const logistics = "map.logistics";
    const { data } = await overallOptions({
      params: [params, bill, logistics],
    });
    const { data: logisticsAttributes } = await getLogisticsAttr();
    const _data = data?.[strHump(params)];
    const billSize = data?.[strHump(bill)]?.bill_size || [];
    if (_data) {
      optionsData.value = {
        ..._data,
        logisticsAttributes,
        bill_size: [{ label: "自定义", value: "custom" }, ...billSize],
        print_count: data?.[strHump(bill)]?.print_count || [],
        mapLogistics: data?.[strHump(logistics)],
      };
    }
  } catch (e) {
    console.error(e);
  }
};

const handleCancel = () => {
  action.setGlobalState({
    changeMicoTabsPath: {
      type: "closeActiveTab",
    },
  });
};

const handleSave = async () => {
  try {
    loading.value = true;

    const { ...channel } = await baseRef.value.submit();
    const additionalInfo = await additionalRef.value.submit();
    const addressInfo = await addressRef.value.submit();
    const transportTypeInfo = await transportTypeRef.value.submit();
    const declareBillInfo = await declareBillRef.value.submit();
    // const channel_surcharge_delete = onlyData.value
    //   ?.filter((item) => item?.id && item?.has_inc_attrs)
    //   ?.filter(
    //     (item) =>
    //       !channel_surcharge
    //         ?.filter((item) => item?.id && item?.has_inc_attrs)
    //         ?.some((n) => n.id === item?.id && n?.has_inc_attrs)
    //   )
    //   .map((item) => ({ ...item, is_delete: 1 }));
    const _api = {
      edit: updateChannel,
      add: channelCreate,
    };
    // let channel_surcharge_all = [
    //   ...channel_surcharge,
    //   ...channel_surcharge_delete,
    // ];
    // let channel_surcharge_all_data = channel_surcharge_all.filter(
    //   (item) => !(!item?.id && item?.cost_attrs?.length == 0)
    // );
    // channel_surcharge_all_data.forEach((item, index) => {
    //   if (item?.id && item?.cost_attrs?.length == 0) {
    //     item.is_delete = 1;
    //   }
    // });
    const res = await _api[isEdit.value ? "edit" : "add"]({
      channel_id: id.value || undefined,
      channel,
      // channel_surcharge: channel_surcharge_all_data,
      channel_attributes: additionalInfo,
      channel_address: addressInfo,
      channel_transport_type: transportTypeInfo,
      channel_declare_bill: declareBillInfo,
    });
    if (res.code !== 200) {
      ElMessage.warning(res.message);
      return;
    }
    ElMessage.success("保存成功");
    handleCancel();
  } catch (e) {
    if (e?.toString().includes(false)) {
      ElMessage.warning("请检查表单信息");
    }
    console.error(e);
  } finally {
    loading.value = false;
  }
};
// const handleActiveIndex = ind =>{
//   tabActive.value = ind.toString()
// }
const handleChange = (val) => {
  switch (val) {
    case "1":
      tabOptions.value = [
        { label: "基本信息" },
        // { label: "运价信息" },
        // { label: "附加费用信息" },
      ];
      break;
    case "2":
      tabOptions.value = [
        { label: "报关参数" },
        { label: "物流面单设置" },
        { label: "报关单设置" },
      ];
      break;
    case "3":
      tabOptions.value = [{ label: "附加属性" }];
      break;
    case "4":
      tabOptions.value = [
        { label: "回邮地址信息" },
        { label: "揽收地址" },
        { label: "境外退件地址" },
      ];
      break;
    case "5":
      tabOptions.value = [{ label: "平台运输方式" }];
      break;
    case "6":
      tabOptions.value = [{ label: "日志" }];
      break;
    default:
      break;
  }
};
</script>
<style lang="scss" scoped>
:deep(.el-tabs) {
  height: 100%;
  .el-tabs__content {
    height: calc(100% - 70px);
    overflow: auto;
  }
  .el-tabs__nav-wrap::after {
    height: 1px;
  }
}
.steps {
  padding-left: 8px;
  :deep(.broadside) {
    margin-top: 0px;
    margin-right: 0px;
  }
}
</style>
